package linkedlist;

/**
 * @author justnow
 * Created on 2020-09-30
 * Description
 *
 * 给定一个链表，删除链表的倒数第 n 个节点，并且返回链表的头结点。
 */
public class Leetcode19_removeNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null)
            return head;
        ListNode dummpy = new ListNode(-1);
        dummpy.next = head;
        ListNode pre = dummpy, last = dummpy;
        while (n + 1 > 0) {
            last = last.next;
            n--;
        }
        while (last != null) {
            pre = pre.next;
            last = last.next;
        }
        ListNode next = pre.next.next;
        pre.next = next;
        return dummpy.next;
    }
}
